const http = require("../../../utils/request");
const culApi = require("../../apis/cultivation");
Page({
  /**
   * 页面的初始数据
   */
  data: {
    enable: false,
    loadingProps: {
      size: '40rpx',
    },
    backTopVisible: false,
    datas:{},
    p_datas:{},
    source:[],
    trans:[],
    imgs:[],
    pics:[],
    canOut:false,
    display:false,
    showImg: false,
    amount:0,
    operation: 0,
    trans_amount:100,
    count:0,
    change_index: 'farmName',
    visible:false,
    p_visable:false,
    padd_visable:false,
    value:"",
    dateTwoVisible: false,
    dateTwo: new Date().getTime(), // 支持时间戳传入
    // 指定选择区间起始值
    start: "2000-01-01",
    end: "2030-09-09",
    type: {
      companyName:"公司",
      farmName:"农场",
      manager:"主管",
      createTime: "创建时间",
      cultivationCode:"养殖批次号",
      remark:"备注",
      picture:"图片",
    },
    policy_type:{
      slogan:"承诺语",
      policyNo:"保单号",
      origin:"保产地",
      standard:"保安全",
    },
    note1: '请选择公司',
    note2: '请选择农场',
    id1:0,
    id2:0,
    policyNo:null,
    policyPlace:null
  },
  confirm_p(){
    http.postRequestBody("/admin/cultivation/"+this.data.datas['cultivationCode']+"/policy/"+this.data.policyNo,{},res=>{
      if(res.data.success){
        wx:wx.showToast({
          title: '成功',
        });
        this.onLoad();
        this.cancel();
      }else{
        wx:wx.showToast({
          title: '失败！',
          icon: "error",
        });
      }
    },err=>{});
  },
  input(e) {
    this.setData({
      value: e.detail.value
    })
  },
  p_input(e){
    let name = e.currentTarget.dataset.data;
    let value = e.detail.value;
    this.setData({
        [`p_datas.${name}`]: value,
    })
    console.log(this.data.p_datas);
  },
  cancel() {
    this.setData({
      value:""
    })
    this.setData({
      visible: false,
      p_visable:false,
      padd_visable:false
    });
  },
  unshow(e) {
    this.setData({
      showImg: e.detail
    })
  },
  ShowImg(e){
    this.setData({
      showImg: true,
      pics: e.currentTarget.dataset.data
    })
  },
  change(e){
    let datas = String(e.currentTarget.dataset.data)
      this.setData({
        visible: true,
        change_index: datas,
        operation: 0,
        value: this.data.datas[datas]
      })
  },
  p_add(){
    let p_datas = {
      slogan:"",
      policyNo:"",
      origin:"",
      standard:"",
      cultivationCode:this.data.datas['cultivationCode'],
      company:"太平洋保险公司",
      pictureUrl:"https://traceability-1258993064.cos.ap-guangzhou.myqcloud.com/clipboard_20230711_021916.png"
    }
    this.setData({
      padd_visable:true,
      p_datas,
    })
  },
  add_promise(){
      let p_datas = this.data.p_datas;
      console.log(p_datas);
      if(p_datas['policyNo']){
        http.postRequestBody("/admin/insurance",
      JSON.stringify(p_datas)
      ,res=>{
        console.log(res);
        if(res.data.success){
          wx:wx.showToast({
            title: '成功',
          });
          this.onLoad();
        }else{
          wx:wx.showToast({
            title: '失败！',
            icon: "error",
          });
        }
        this.cancel();
      },err=>{});
      }else{
        wx:wx.showToast({
          title: '保单号不能为空',
          icon: "error",
        });
      }
  },
  change_pic(e){
    let datas = String(e.currentTarget.dataset.data)
    let imgs = [];
    let pic = this.data.datas['picture']
    console.log(pic);
    if(pic){
      for(let i = 0;i<pic.length;i++) {
        console.log(pic[i]);
        imgs.push({
          name: pic[i],
          url: pic[i],
          type: 'image',
          status: "done",
        })
      }
    }
    this.setData({
      change_index: datas,
      operation: 1,
      imgs,
    })
  },
  copy(e) {
    let datas = String(e.currentTarget.dataset.data)
    if(datas === 'undefined' || datas === '') {
      datas = null
    }
    wx.setClipboardData({
      data: datas,
      success: (res) => {
        wx.getClipboardData({
          success: (option) => {
            wx.showToast({
              title: '复制成功',
            })
          },
          fail: (res) => {
          },
          complete: (res) => {},
        })
      },
      fail: (res) => {
        wx.showToast({
          title: '复制失败',
          icon: 'error',
        })
      },
      complete: (res) => {},
    })
  }, 
  onUpload(file) {
    const { imgs } = this.data;
    const { length } = imgs;
    this.setData({
      imgs: [...this.data.imgs,{...file,status:'loading'}],
      display: true
    });  
    const task = wx.uploadFile({
      url: 'https://37y5825u15.oicp.vip/admin/cos/upload', // 仅为示例，非真实的接口地址
      filePath: file.url,
      name: 'file',
      formData: { user: 'test' },
      success: (res) => {
        this.setData({
          [`imgs[${length}].status`]: 'done',
          [`imgs[${length}].url`]: JSON.parse(res.data).data,
          [`datas.picture[${length}]`]: JSON.parse(res.data).data,
          [`imgs[${length}].percent`]: res.progress,
          display: false,
        });
      },
    });
    task.onProgressUpdate((res) => {
      this.setData({
        [`imgs[${length}].percent`]: res.progress,
        [`imgs[${length}].status`]: 'loading',
      });
    });
  },
  handleSuccess(e) {
    const { files } = e.detail;
    this.onUpload(files[files.length-1]);
  },
  handleRemove(e) {
    const { index } = e.detail;
    const { imgs } = this.data;
    imgs.splice(index, 1);
    let data = this.data.datas
    data['picture'].splice(index,1)
    console.log('pic',data);
    this.setData({
      imgs,
      data
    });
  },
  handleClick(e) {
    console.log(e.detail.file);
  },
  open_source() {
    let data = getApp().globalData
    data.source_data = this.data.source;
    data.codeing = this.data.datas.cultivationCode;
    wx:wx.navigateTo({
      url: '/pages/cultivation/product/Source/source',
      events: null,
      routeType: 'routeType',
      success: (result) => {
      },
      fail: (res) => {
      },
      complete: (res) => {},
    })
  },
  showCascader() {
    this.setData({ visiblec: true });
  },
  onChange(e) {
    const { selectedOptions } = e.detail;
    console.log(selectedOptions);
    this.setData({
      id1: selectedOptions[0]?selectedOptions[0]['value']:null,
      id2: selectedOptions[1]?selectedOptions[1]['val']:null,
      note1: selectedOptions[0]?selectedOptions[0]['label']:null,
      note2: selectedOptions[1]?selectedOptions[1]['label']:null,
    });
  },
  open_trans(){
    let data = getApp().globalData
    data.trans_data = this.data.trans;
    data.codeing = this.data.datas.cultivationCode
    wx:wx.navigateTo({
      url: '/pages/cultivation/product/Trans/trans',
      events: null,
      routeType: 'routeType',
      success: (result) => {},
      fail: (res) => {},
      complete: (res) => {},
    })
  },
  open_promise(){
    this.setData({
      p_visable:true
    })
  },
  showDialog(e) {
    this.setData({
      showWarnConfirm:true,
    })
  },
  closeDialog() {
    this.setData({
      showWarnConfirm:false,
    })
  },
  del_promise(){
    http.delRequest("/admin/insurance/"+this.data.datas['insuranceId'],{},res=>{
      if(res.data.success){
        wx:wx.showToast({
          title: '删除成功',
        });
        this.onLoad();
      }else{
        wx:wx.showToast({
          title: '删除失败！',
          icon: "error",
        });
      }
      this.closeDialog();
      this.cancel();
    },err=>{});
  },
  change_promise(){
    let p_datas = this.data.p_datas;
    console.log('change',p_datas);
    if(p_datas['policyNo']!=""){
      http.putRequest("/admin/insurance",
      JSON.stringify(p_datas)
    ,res=>{
      console.log('change',res);
      if(res.data.success){
        wx:wx.showToast({
          title: '成功',
        });
        this.onLoad();
      }else{
        wx:wx.showToast({
          title: '失败！',
          icon: "error",
        });
      }
      this.cancel();
    },err=>{});
    }else{
      wx:wx.showToast({
        title: '保单号不能为空',
        icon: "error",
      });
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    http.getRequest('/admin/company/all',{},res=>{
      this.setData({
        company: res.data.data
      })
      let data = res.data.data;
      let arr = [];
      for(let i = 0;i<data.length;i++){
        let chi = [];
        if(data[i]['farms']){
          for(let v of data[i]['farms']){
            chi.push({
              label: v['farmName'],
              value: data[i]['id']+''+v['id'],
              val: v['id']
            })
          }
        }else{
          chi.push({
            label: '无',
            value: -1,
          })
        }
      arr.push({
        label: data[i]['companyName'],
        value: data[i]['id'],
        children: chi
      })
      this.setData({
        options: arr,
      })
    }
    },err=>{})
    let data = getApp().globalData.farm_data;
    let breed = data.cultivationCode;
    culApi.getCultivation(null,null,null,breed).then((datas)=>{
      this.setData({
        datas: datas,
        id1: datas['companyId'],
        id2: datas['farmId'],
        note1: datas['companyName'],
        note2: datas['farmName'],
      })
      if(datas['state']!=='CREATED'&&datas['state']!=='ENCLOSURE'){
        this.setData({
          canOut: true,
        })
      }
      if(datas['insuranceId']){
        http.getRequest("/admin/insurance/"+datas['insuranceId'],{},res=>{
          console.log('保障',res);
          this.setData({
            p_datas: res.data.data || {}
          })
        },err=>{});
      }
    })
    http.getRequest("/admin/cultivation/"+breed+"/operation",{},res=> {
      this.setData({
        source: res.data.data
      })
    })
    http.getRequest("/admin/cultivation/"+breed+"/dispatch",{},
    res=>{
      let count = 0;
      for(let v of res.data.data){
        count += v.count
      }
      this.setData({
        trans: res.data.data,
        count: count
      })
      },err=>{})
  },
  confirm_change(){
    this.setData({
      operation: 0
    })
    console.log(this.data.datas);
    http.putRequest('/admin/cultivation',
    JSON.stringify(this.data.datas)
  ,res => {
    wx:wx.showToast({
      title: '修改成功',
    });
    this.onLoad()
  },err=>{})
  },
  confirm(){
    let datas = this.data.datas
    if(this.data.change_index!=='farmName'&&this.data.change_index!=='companyName'&&this.data.change_index!=='policyNo'){
      datas[this.data.change_index] = this.data.value
      this.setData({
        value: this.data.value
      })
    }else{
      datas['companyId'] = this.data.id1;
      datas['farmId'] = this.data.id2;
      datas['companyName'] = this.data.note1;
      datas['farmName'] = this.data.note2;
    }
    if(!this.data.datas['farmId']){
      wx:wx.showToast({
        title: '未设置农场！',
        icon: 'error'
      })
      return ;
    }
    this.setData({
      datas,
    })
    http.putRequest('/admin/cultivation',
      JSON.stringify(this.data.datas)
    ,res => {
      wx:wx.showToast({
        title: '修改成功',
      });
      this.onLoad();
    },err=>{})
    this.cancel();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.onLoad()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onRefresh() {
    this.setData({ enable: true });
    this.onLoad();
    setTimeout(() => {
      this.setData({ enable: false });
    }, 500);
  },
  onScroll(e) {
    const { scrollTop } = e.detail;
    this.setData({
      backTopVisible: scrollTop > 100,
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  
})